package com.study.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.core.error.ErrorUtil;
import com.study.core.resp.Resp;
import com.study.model.entity.User;
import com.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/study-app/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/batchAdd")
    public Resp batchAdd(@RequestBody List<User> userList) {
        System.out.println("batchAdd:");
        userList.forEach(System.out::println);
        userService.saveBatch(userList);
        return Resp.ok();
    }

    @PostMapping("/batchDel")
    public Resp batchDel(@RequestBody List<Long> ids) {
        System.out.println("batchDel: " + JSONUtil.toJsonStr(ids));
        userService.removeBatchByIds(ids);
        return Resp.ok();
    }

    @GetMapping("/getById")
    public Resp<User> getById(Long id){
        System.out.println("getById: " + id);
        // 模拟报错
        if (id <= 0) { ErrorUtil.throwBizError("参数错误！"); }
        return Resp.ok(userService.getById(id));
    }

    @GetMapping("/getByPage")
    public Resp<IPage<User>> getByPage(Long pageNum, Long pageSize, String account){
        System.out.println("getByPage: pageNum" + pageNum + ", pageSize: " + pageSize + ", account: " + account);
        if (pageNum == null || pageNum <= 0) { pageNum = 1L; }
        if (pageSize == null || pageSize <= 0) { pageSize = 10L; }
        IPage<User> page = new Page<>(pageNum, pageSize);
        Wrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .like(StrUtil.isNotBlank(account), User::getAccount, account)
                .orderByDesc(User::getCreateTime);
        return Resp.ok(userService.page(page, wrapper));
    }

    @PostMapping("/updateUser")
    public Resp updateUser(User user) {
        System.out.println("updateUser: " + user);
        userService.updateById(user);
        return Resp.ok();
    }

    @PostMapping("/updateUserByJson")
    public Resp updateUserByJson(@RequestBody User user) {
        System.out.println("updateUserByJson: " + user);
        userService.updateById(user);
        return Resp.ok();
    }
}
